import pandas as pd

from database.mysql_utils import MysqlConnect


def save_df_to_mysql_stock_sales(
    df: pd.DataFrame,
    table_name: str,
    if_exists: str = 'append',
    chunk_size: int = 1000,
    engine=None
) -> bool:
    """
    将 DataFrame 保存到 stock_sales 库
    """
    try:
        # 如果没有提供engine，使用默认配置创建
        if engine is None:
            engine = MysqlConnect.mysql_connect_stock()
            
        # 确保DataFrame不为空
        if df.empty:
            print(f"警告: DataFrame为空，未执行保存操作")
            return False
            
        # 执行保存操作
        df.to_sql(
            name=table_name,
            con=engine,
            if_exists=if_exists,
            index=False,
            chunksize=chunk_size
        )
        
        print(f"====成功保存{len(df)}条数据到表{table_name}====")
        return True
        
    except Exception as e:
        print(f"****保存数据到MySQL失败: {str(e)}*****")
        return False
    
    finally:
        # 如果是新创建的engine，关闭连接
        if engine is not None and engine != MysqlConnect.mysql_connect():
            engine.dispose()


